using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Services.Impl;

/// <summary>
/// 点检标件查询服务。
/// </summary>
internal sealed class StandardPartsQueryService(
    IRepository<EquipInspectionStandardParts> standardpartsRepo,
    IRepository<EquipInspectionPlan> planRepo) : IStandardPartsQueryService
{
    public async Task<(bool isStandardParts, bool needInspect)> IsStandardPartsAndWorkAsync(string sn, long lineId, long workstationId, CancellationToken cancellationToken = default)
    {
        // 检查是否为标件（可用状态）
        var standardParts = await standardpartsRepo.FirstOrDefaultAsync(m => m.StandardPartNo == sn && m.Status == EnabledStatusEnum.Enabled, cancellationToken);
        if (standardParts == null)
        {
            return (false, false);
        }

        // 检查当前工位是否为标件点检工位
        if (standardParts.LineId != lineId || !standardParts.WorkstationIds.Contains(workstationId))
        {
            return (true, false);
        }

        // 检查此工位上是否有存在设备且有设置自动检计划
        var exists = await planRepo.AsQueryable()
            .Includes(m => m.Machinery)
            .AnyAsync(m => m.Machinery!.LineId == lineId && m.Machinery.WorkstationId == workstationId
                && m.InspectType == InspectTypeEnum.Auto
                && m.Status == EnabledStatusEnum.Enabled, cancellationToken);

        return (true, exists);
    }
}
